import { createSlice,createAsyncThunk } from "@reduxjs/toolkit";
import {
  getGoodPriceFetch,
  getHomeHighScoreFetch,
  getDiscountFetch,
  getHotrecommendFetch,
  getLongforFetch,
  getPlusFetch
} from '@/services'

// 定义异步请求但await还是阻塞式执行,定义前缀为了调试找到数据
/*export const getGoodHomeAsync = createAsyncThunk('getGoodHomeAsync',async () => {
  const res = await getGoodPriceFetch()
  const res2 = await getHomeHighScoreFetch()
  // 这样返回的数据不好处理
  return {res,res2}
})
*/

// 直接使用promise执行
export const getGoodHomeAsync = createAsyncThunk('getGoodHomeAsync', (payload, {dispatch}) => {
  // 性价比房源
  getGoodPriceFetch().then(res => {
    dispatch(changeGetGoodPriceAction(res))
  })
  // 高分房源
  getHomeHighScoreFetch().then(res => {
    dispatch(changeGetHighScoreAction(res))
  })
  // 折扣房源
  getDiscountFetch().then(res => {
    dispatch(changeGetDiscountAction(res))
  })
  // 推荐房源
  getHotrecommendFetch().then(res => {
    dispatch(chnageGetHotrecommendAction(res))
  })
  // 向往城市房源
  getLongforFetch().then(res => {
    dispatch(chnageGetLongforAction(res))
  })

  getPlusFetch().then(res => {
    dispatch(changeGetPlusAction(res))
  })
})



const homeSlice = createSlice({
  name:"home",
  // 定义初始数据
  initialState:{
    goodPriceState: {},
    highScoreState: {},
    discountState: {},
    hotrecommendState:{},
    longforState: {},
    plusState: {},
  },
  // 更新数据
  reducers:{
    changeGetGoodPriceAction: (state,{payload}) => {
      state.goodPriceState = payload
    },
    changeGetHighScoreAction: (state, {payload}) => {
      state.highScoreState = payload
    },
    changeGetDiscountAction: (state, {payload}) => {
      state.discountState = payload
    },
    chnageGetHotrecommendAction: (state,{payload}) => {
      state.hotrecommendState = payload
    },
    chnageGetLongforAction: (state, {payload}) => {
      state.longforState = payload
    },
    changeGetPlusAction: (state, {payload}) => {
      state.plusState = payload
    }
  },
  extraReducers: {
    // 监听异步请求：到对应的状态执行对应的操作，返回数据到state中
    // [getGoodHomeAsync.fulfilled](state,{payload}){
    //   console.log(payload);
    //   state.goodPriceState = payload
    // }
  }
})



export const {
  changeGetGoodPriceAction,
  changeGetHighScoreAction,
  changeGetDiscountAction,
  chnageGetHotrecommendAction,
  chnageGetLongforAction,
  changeGetPlusAction
} = homeSlice.actions
export default homeSlice.reducer